'use strict';
const Controller = require('egg').Controller;
class BannerController extends Controller {
    // 新增 编辑  轮播图
    async edit() {
        const { ctx, app } = this
        const { id, title, path_url, sort, image_url, statr_time, end_time } = ctx.request.body
        // 验证参数
        ctx.validate({
            title: { type: 'string', required: true, desc: '标题' },
            image_url: { type: 'string', required: true, desc: '图片路径' },
            statr_time: { type: 'int', required: true, desc: '展示开始时间' },
            end_time: { type: 'int', required: true, desc: '结束时间' },
        });
        let list
        if (id == 0) {  //创建 
            list = await app.model.Banner.create({
                title, path_url, sort, image_url, statr_time, end_time
            })
        } else { //修改
            let oneList = await app.model.Banner.findByPk(id)
            if (!oneList) {
                ctx.throw(400, '数据不存在')
            }
            list = await oneList.update({
                title, path_url, sort, image_url, statr_time, end_time
            })
        }
        ctx.apiSuccess(list)
    }
    // 查询 所以 轮播图
    async list() {
        const { ctx, app } = this
        let newTime = new Date()
        let title = ctx.query.title
        let where = {}, Op = app.Sequelize.Op;

        if (title != '' && title != undefined) {
            where.title = {
                [Op.like]: '%' + title + '%'
            }
        }
        let list = await ctx.page(app.model.Banner, where)
        ctx.apiSuccess({ list, newTime })
    }
    //删除
    async del(){
        const {ctx,app}=this
        const id=ctx.params.id
        ctx.validate({
            id:{
                type:'int',
                required:true,
                desc:'id'
            }
        })
        const list=await app.model.Banner.findByPk(id)
        if(!list){
            ctx.throw(400,'数据不存在')
        }
        list.destroy()
        ctx.apiSuccess('删除成功')
    }
}
module.exports = BannerController;

